package com.atjava.webspider.logic;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.atjava.webspider.consts.Const;
import com.atjava.webspider.model.DatabaseConfig;
import com.atjava.webspider.model.Site;
import com.atjava.webspider.util.FileSystemUtil;
import com.atjava.webspider.util.RegexpUtil;
import com.atjava.webspider.util.XmlUtil;

public class DatabaseLogic {
	
	public String createSql(String folder,String sqlTmplt,int dataNum,String outCharset)throws Exception{
		StringBuffer sql = new StringBuffer();
		List<File> dataFiles = FileSystemUtil.getFilesList(new File(folder), "xml");
		String fileCharset = null;
		for (int i = 0; i < dataFiles.size(); i++) {
			File xmlFile = dataFiles.get(i);
			if(!XmlUtil.isDataFile(xmlFile))
				continue;
			//站点名称
			String siteName = xmlFile.getName().split(Const.DATA_NAME_SEPARATOR)[0];
			//站点对象
			Site site = (Site)CommonLogic.getByName
				(ConfigLogic.getSiteConfig().getSites(), siteName);
			
			Map<String, String> varMap = XmlUtil.readVarMap(xmlFile, site.getCharset());
			
			//读取变量错误
			if(varMap.size() == 0)
				continue;
			
			//数据量变量
			varMap.put(Const.DATA_NUM_VAR_NAME, String.valueOf(dataNum));
			
			Iterator<String> varIter = varMap.keySet().iterator();
			String sqlText = sqlTmplt;
			while (varIter.hasNext()) {
				String name = varIter.next();
				String value = varMap.get(name);
				//方言处理
				value = CommonLogic.getDbValueProcsor().prcsValue(value);
				value = 
				sqlText = RegexpUtil.replaceAll
				(sqlText, VarLogic.getVarExp(name), value);
			}
			sql.append(sqlText);
			sql.append(";\r\n");
		}
		if(fileCharset == null)
			return sql.toString();
		else
			return new String(sql.toString().getBytes(fileCharset),outCharset);
	}
	
	public void deleteConfig(String name){
		
		List<DatabaseConfig> configs = ConfigLogic.getDbConfig().getConfigs();
		for (int i = 0; i < configs.size(); i++) {
			
		}
	}
	
}
